<?php
namespace  crontab\event;
//设置时区
date_default_timezone_set('PRC');
use Workerman\Crontab\Parser;
use Workerman\MySQL\Connection;
use Workerman\Crontab\Crontab;
use Workerman\Lib\Timer;
require_once dirname(__DIR__).'/db_config.php';
class HttpEvent {
	//任务和定时任务的映射池
    public  static $taskPools= [];


    public  static  $taskConnAddr = 'Text://127.0.0.1:12341';
	//主进程初始化子进程的回调函数
    public static function onWorkerStart($worker){
        //加载任务
        $list  = self::getAllJobs();
        if($list){
            foreach ($list as $v) {
                $id  = $v['id'];
                $job = new Crontab($v['rule'], function() use($id,&$job){
                    if(property_exists($job,'stop')){
                        return false;
                    }
                    // 与远程task服务建立异步连接
                   self::sendAsyMag($id);
                });

                if($v['status'] == 1){
                    $job->stop=true;
                }
                self::$taskPools[$id] =$job;
            }
        }
    }

    //初始化进程异步连接通信
    public static  function sendAsyMag($id){
          //初始化连接
        $conn = new \Workerman\Connection\AsyncTcpConnection(self::$taskConnAddr);
        $conn->send($id);
        $conn->connect();
    }

    public static function onMessage($http_connection, $request) {
        $post = $request->post();
        $id   = $post['id']??0;
        $action = $post['action']??'';

        if(!$id){
            $http_connection->send(self::error(201,'id error'));
        }

         if(!$action){
            return 'action not existents';
        }
        if($action == 'add'){
            $isok = self::addTask($post);
            if(!is_bool($isok)){
                $http_connection->send(self::error(201,$isok));
            }
            $http_connection->send(self::success());

        }else if($action  == 'delete'){

            //1.先判断定时任务是否存在  存在先进行删除
            $isok = self::taskIsExist($id);
             if($isok){
                $http_connection->send(self::success());
            }else{
                $http_connection->send(self::error(201,'fail'));
            }

        }else if($action  == 'execute'){  // 执行任务

            self::sendAsyMag($id);
            $http_connection->send(self::success());

        }else if($action  == 'suspend'){  // 暂停任务

            if(isset(self::$taskPools[$id])){
                self::$taskPools[$id]->stop = true;
                $http_connection->send(self::success());
            }
            $http_connection->send(self::error(201,'fail'));

         }else if($action  == 'startUp'){  // 启动任务

            if(isset(self::$taskPools[$id])){
                if(property_exists(self::$taskPools[$id],'stop')){
                    unset(self::$taskPools[$id]->stop);
                    $http_connection->send(self::success());
                }
                $http_connection->send(self::success());
            }
            $http_connection->send(self::error(201,'fail'));

         }

        $http_connection->send(self::error(201,'unknown error'));
    }



    public static function onClose($connection){

    }

    public static function onWorkerStop($worker){
    	
    }

    public static function onWorkerReload($worker){
    	
    }
    public static function onError($connection){
    	
    }

    //添加任务
    public  static function addTask($post){
        $id = $post['id']??'';
        $rule = $post['crontab']??'';
        
        if(!$id){
            return 'id not existents';
        }

        if(!$rule){
            return 'crontab rule not existents';
        }

        //判断 crontab 规则是否有效
        $isok = (new Parser())->isValid($rule);
        if(!$isok){
            return 'crontab rule error';
        }
        //1.先判断定时任务是否存在  存在先进行删除
        self::taskIsExist($id);

        $job = new Crontab($post['crontab'], function() use($id,&$job) {
            if(property_exists($job,'stop')){
                return false;
            }
            // 与远程task服务建立异步连接
            self::sendAsyMag($id);
        });
        self::$taskPools[$id] =$job;
        return true;
    }

    //判断任务是否存在
    public  static function  taskIsExist($id){
        if(isset(self::$taskPools[$id])){
            self::$taskPools[$id]->stop = true;
            //销毁这个定时类
            self::$taskPools[$id]->destroy();
            //销毁数组变量
            unset(self::$taskPools[$id]);
            return true;
        }
        return false;
    }

    //获取所有任务
    public static  function  getAllJobs(){
        global $db_config;
        $db = new \Workerman\MySQL\Connection(
            $db_config['host'], 
            $db_config['port'], 
            $db_config['user'], 
            $db_config['password'], 
            $db_config['database']
        );
        $list= $db->select('id,rule,status')->from('we_task')
            ->where('status in (1,2) AND delete_time = 0')
            ->query();
        //销毁链接
        unset($db);
        return  $list;
    }

    public static function  responseJson($code,$msg){
        $data['code'] = $code;
        $data['msg'] = $msg;
        return json_encode($data);
    }

    public static function  success($msg='success'){
        return self::responseJson(200,$msg);
    }

    public static function  error($code,$msg='fail'){
        return self::responseJson($code,$msg);
    }


}
